"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : rename table jdbc调用兼容A库、兼容B库执行
Create At   : 2023/02/25
Owner       : @peilinqian
Description :
    step1:创建普通库（默认兼容A库）;
    step2:创建兼容B库;
    step3:远程复制java脚本至指定主机;
    step4:编译java文件;
    step5:运行java程序;
Expect      :
    step1:创建普通库（默认兼容A库）; expect:创建成功
    step2:创建兼容B库; expect:创建成功
    step3:远程复制java脚本至指定主机; expect:复制成功
    step4:编译java文件; expect:编译成功
    step5:运行java程序; expect:执行结果正确
History     :
            modified by zwx1128488 at 2023/08/22 创建B库后执行语句激活插件
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class JDBCPrepareStatement(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info("----this is setup----")
        self.log.info(f'----{os.path.basename(__file__)}:start----')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.pri_root = Node(node='PrimaryRoot')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.db_a_name = 'db_renametable_0003_a'
        self.db_b_name = 'db_renametable_0003_b'
        self.target_path = os.path.join(macro.DB_BACKUP_PATH, "JDBC_test")
        self.java_name = "Compatibility_Grammar_Renametable_Case0003"
        self.com = Common()
        self.constant = Constant()
        self.suc_flag = 'rename table success'

    def test_main(self):
        step_txt = '----step1:创建普通库（默认兼容A库）; expect:创建成功----'
        self.log.info(step_txt)
        create_sql = f"drop database if exists {self.db_a_name};" \
            f"create database {self.db_a_name};"
        create_result = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, create_result,
                      '执行失败' + step_txt)

        step_txt = '----step2:创建兼容B库; expect:创建成功----'
        self.log.info(step_txt)
        create_sql = f"drop database if exists {self.db_b_name};" \
            f"create database {self.db_b_name} dbcompatibility='B';"
        create_result = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, create_result,
                      '执行失败' + step_txt)
        enable_sql = f"show plugins;"
        enable_result = self.pri_sh.execut_db_sql(enable_sql,
                                                  dbname=self.db_b_name)
        self.log.info(enable_result)
        self.assertIn('rows', enable_result, '连接失败')

        step_txt = '----step3:远程复制java脚本至指定主机; expect:复制成功----'
        self.log.info(step_txt)
        self.com.scp_file(self.pri_root, f"{self.java_name}.java",
                          self.target_path)
        check_cmd = f'ls {self.target_path}'
        check_result = self.pri_root.sh(check_cmd).result()
        self.assertIn(self.java_name, check_result, '执行失败' + step_txt)

        step_txt = '----step4:编译java文件; expect:编译成功----'
        self.log.info(step_txt)
        self.pri_root.scp_put(macro.JDBC_PATH,
                              f"{self.target_path}/postgresql.jar")
        javac_cmd = f"javac -encoding utf-8 -cp " \
            f"{os.path.join(self.target_path, 'postgresql.jar')} " \
            f"{os.path.join(self.target_path, f'{self.java_name}.java')}"
        self.log.info(javac_cmd)
        javac_result = self.pri_root.sh(javac_cmd).result()
        self.log.info(javac_result)
        self.assertEqual('', javac_result, "执行失败" + step_txt)

        step_txt = '----step5:运行java程序; expect:执行结果正确----'
        self.log.info(step_txt)
        url_host_port = f"{self.pri_dbuser.db_host}:{self.pri_dbuser.db_port}"
        java_cmd = f"java -cp " \
            f"{os.path.join(self.target_path, 'postgresql.jar')}" \
            f":{self.target_path} " \
            f"{self.java_name} {url_host_port} {self.db_a_name} " \
            f"{self.db_b_name} {self.pri_dbuser.db_user} " \
            f"{self.pri_dbuser.db_password}"
        self.log.info(java_cmd)
        java_result = self.pri_root.sh(java_cmd).result()
        self.log.info(java_result)
        self.assertIn(self.suc_flag, java_result, "执行失败" + step_txt)

    def tearDown(self):
        self.log.info('----this is teardown----')
        step_txt1 = '----删除普通库及B库; expect:删除成功----'
        self.log.info(step_txt1)
        drop_sql = f"drop database if exists {self.db_a_name};" \
            f"drop database if exists {self.db_b_name};"
        drop_result3 = self.pri_sh.execut_db_sql(drop_sql)
        self.log.info(drop_result3)
        step_txt2 = '----清理编译脚本; expect:清理成功----'
        self.log.info(step_txt2)
        file_rm_cmd = f'rm -rf {self.target_path};' \
            f'if [ -d {self.target_path} ]; ' \
            f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(file_rm_cmd)
        file_rm_result = self.pri_root.sh(file_rm_cmd).result()
        self.log.info(file_rm_result)

        self.log.info('----清理环境断言----')
        self.assertEqual(drop_result3.count(
            self.constant.DROP_DATABASE_SUCCESS), 2, '执行失败' + step_txt1)
        self.assertEqual('not exists', file_rm_result, "执行失败" + step_txt2)

        self.log.info(f'----{os.path.basename(__file__)}:end----')
